package handler

import (
	"context"
	"encoding/json"
	"errors"
	"server/basic/config"
	"server/basic/dao"
	"server/basic/model"
	"server/basic/proto/good"
	"time"
)

type Server struct {
	good.UnimplementedGoodServerServer
}

func (s *Server) UserLogin(_ context.Context, req *good.UserLoginReq) (*good.UserLoginResp, error) {
	name, err := dao.UserName(req.Name)
	if err != nil {
		return nil, err
	}
	if name.Password != req.Password {
		return nil, errors.New("密码错误")
	}
	return &good.UserLoginResp{Id: int32(name.Id)}, nil
}
func (s *Server) TakeList(_ context.Context, req *good.TakeListReq) (*good.TakeListResp, error) {
	takes := []model.TakeSoutFoods{}
	val := config.Rdb.Get(context.Background(), "keyone").Val()
	if val == "" {
		//config.Rdb.SetEX(context.Background(), "ssss", 2, 10*time.Second)
		take, err := dao.Take()
		if err != nil {
			return nil, err
		}
		takes = take
		marshal, err := json.Marshal(take)
		if err != nil {
			return nil, err
		}
		config.Rdb.Set(context.Background(), "keyone", marshal, 30*time.Second)

	} else {
		json.Unmarshal([]byte(val), &takes)
	}

	takelist := []*good.TakeList{}
	for _, foods := range takes {
		takelist = append(takelist, &good.TakeList{
			CompleteTheOrderToday:               foods.CompleteTheOrderToday,
			NewUsersAddedThisWeek:               foods.NewUsersAddedThisWeek,
			CheckInStoreThisWeek:                foods.CheckInStoreThisWeek,
			RecruitingDeliveryPersonnelThisWork: foods.RecruitingDeliveryPersonnelThisWork,
		})
	}
	return &good.TakeListResp{Take: takelist}, nil
}
